package com.easyui.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.easyui.bean.*;
import com.easyui.common.*;

public class DownloadServlet extends HttpServlet {

	public DownloadServlet() {}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.reset();//清空缓冲区, 防止页面中的空行等输出到下载内容里去
		response.setContentType("application/x-download");
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		
		
		int ano = Integer.parseInt(request.getParameter("ano"));
		String fileName = "";
		String saveName = "";

		if(fileName == null || saveName == null || fileName.trim().equals("") || saveName.trim().equals("")) {
			Map<String, String> attach = new SelAttach().getAttach(ano);
			fileName = attach.get("aname");
			saveName = attach.get("savename");
			System.out.println(fileName + ":f");
			System.out.println(saveName + ":s");
		}
		
		String servletPath = this.getServletContext().getRealPath("/");
		String uploadFile = "uploadFile";
		String savePath = "" + servletPath + uploadFile + "\\" + saveName;
		
		File file = new File(savePath);
		InputStream is = new FileInputStream(file);
		OutputStream os = response.getOutputStream();
		
		try {
			//解决文件下载文件名乱码的问题
			if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {//IE浏览器
				fileName = URLEncoder.encode(fileName, "UTF-8");
			} else { //其他浏览器
				fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
			}
			//添加头信息
			response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Content-Length", (new Long(file.length())).toString());
			
			int i = -1;
			byte b[] = new byte[1024];
			i = is.read(b);
			while(i != -1) {
				os.write(b, 0, i);
				i = is.read(b);
			}
		} catch(FileNotFoundException e) {
			System.out.println("找不到文件");
			e.printStackTrace();
		}
		
		is.close();
		os.flush();
		os.close();
	}

}
